import { getCurrentInstance } from "./component"

export function provide(key, value) {
  const instance:any = getCurrentInstance()
  let {provides, parent} = instance
  if(parent) {
    const {provides: parentProvide} = parent
    if(provides === parentProvide) {
      provides = instance.provides = Object.create(parentProvide) //原型链取值
    }
  }
  provides[key] = value
}

export function inject(key, defaultValue) {
  const instance:any = getCurrentInstance()
  const {parent} = instance
  if(parent) {
    const {provides: parentProvides} = parent
    if(key in parentProvides) {
      return  parentProvides[key]
    } else {
      return typeof defaultValue === 'function' ? defaultValue() : defaultValue
    }
  }
}